<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends BaseController {

	function Auth() {
		parent::BaseController ();
		
		$this->_template = $this->config->item("admin-template");
		$this->_layout = "simple";
		
		$this->load->library('Form_validation');
		$this->load->library('DX_Auth');
		
		$this->load->helper('url');
		$this->load->helper('form');
		
		$this->load->helper('language');

		$this->lang->load('admin');
	}

	function login() {
		if ( ! $this->dx_auth->is_logged_in()){
			$val = $this->form_validation;
				
			// Set form validation rules
			$val->set_rules('username', 'Username', 'trim|required|xss_clean');
			$val->set_rules('password', 'Password', 'trim|required|xss_clean');
			$val->set_rules('remember', 'Remember me', 'integer');

			// Set captcha rules if login attempts exceed max attempts in config
			if ($this->dx_auth->is_max_login_attempts_exceeded()){
				$val->set_rules('captcha', 'Confirmation Code', 'trim|required|xss_clean|callback_captcha_check');
			}

			if ($val->run() AND $this->dx_auth->login($val->set_value('username'), $val->set_value('password'), $val->set_value('remember'))){
				//Si es administrador, lo mandaremos al portal
				if($this->dx_auth->is_role("admin")){
					redirect ('admin');
				} else{
					redirect ('');
				}
			} else{
				// Check if the user is failed logged in because user is banned user or not
				if ($this->dx_auth->is_banned()){
					// Redirect to banned uri
					$this->dx_auth->deny_access('banned');
				} else{
					// Default is we don't show captcha until max login attempts eceeded
					$this->_addData("show_captcha", FALSE);

					// Show captcha if login attempts exceed max attempts in config
					if ($this->dx_auth->is_max_login_attempts_exceeded()){
						// Create catpcha
						$this->dx_auth->captcha();

						// Set view data to show captcha on view file
						$this->_addData("show_captcha", TRUE);
					}
						
					// Load login page view
					$this->_render();
				}
			}
		} else {
			if($this->dx_auth->is_role("admin")){
				redirect ('admin');
			} else{
				redirect ('');
			}
		}
		
	}

	function logout() {
		$this->dx_auth->logout();

		redirect('');
	}
}
?>